<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>使用原生的js模拟jq的get请求</h1>
    <button class="btn1">点击我发送get形式的ajax</button>
    <script>
      class Jq {
        ajax(options) {
          let {
            url = "",
            method = "get",
            data = {},
            dataType = "json",
            success = function () {},
          } = options;
          let str = this.#o2s(data);
          url = url + "?" + str;
          let xhr = new XMLHttpRequest();
          xhr.open(method, url);
          xhr.send();
          xhr.onload = function () {
            if (xhr.status >= 200 && xhr.status < 300) {
              if (dataType == "text") {
                success(xhr.responseText);
              } else {
                success(JSON.parse(xhr.responseText));
              }
            }
          };
        }
        // 把data对象转换成字符串
        #o2s(obj) {
          let keys = Object.keys(obj);
          let values = Object.values(obj);
          let arr = keys.map((key, k) => {
            return `${key}=${values[k]}`;
          });
          return arr.join("&");
        }
      }

      let $ = new Jq();
      // 点击btn1发送ajax
      let btn1 = document.querySelector(".btn1");
      btn1.onclick = function () {
        $.ajax({
          url: "/getdata",
          method: "get",
          data: {
            myname: "zhangsan",
            age: 20,
            height: "178cm",
          },
          dataType: "text",
          success: function (res) {
            // 定义success函数
            console.log(res);
          },
        });
      };

      // 1.promise封装  2.区分post请求
    </script>
  </body>
</html>
